package com.jzy.gulimall.cart.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.TypeReference;
import com.jzy.common.constant.CartConstant;
import com.jzy.common.utils.R;
import com.jzy.gulimall.cart.feign.ProductFeignService;
import com.jzy.gulimall.cart.interceptor.CartInterceptor;
import com.jzy.gulimall.cart.service.CartService;
import com.jzy.gulimall.cart.util.RedisUtil;
import com.jzy.gulimall.cart.vo.CartItemVo;
import com.jzy.gulimall.cart.vo.CartVo;
import com.jzy.gulimall.cart.vo.SkuInfoVo;
import com.jzy.gulimall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author jzy
 * @date 2020/9/18 14:21
 */
@Service
public class CartServiceImpl implements CartService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private ProductFeignService productFeignService;

    /**
     * 购物车 添加商品 自动判断登录类型
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        String cartKey = getCartKey();
        return addCartItem(skuId, num, cartKey);
    }

    /**
     * 购物车 添加商品 合并购物车时,登录状态未即使更新,手动传递userId
     */
    private CartItemVo addCartItem(Long skuId, Integer num, String cartKey) throws InterruptedException, ExecutionException {
        CartItemVo hget = (CartItemVo) redisUtil.hget(cartKey, skuId.toString());
        if (hget != null) {
            //购物车有此商品
            hget.setCount(hget.getCount() + num);
            redisUtil.hset(cartKey, skuId.toString(), hget);
            return hget;
        }
        //远程查询sku信息
        CartItemVo cartItemVo = new CartItemVo();
        CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
            R info = productFeignService.getSkuInfo(skuId);
            SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
            });
            cartItemVo.setCheck(true);
            cartItemVo.setCount(num);
            cartItemVo.setImage(skuInfo.getSkuDefaultImg());
            cartItemVo.setTitle(skuInfo.getSkuTitle());
            cartItemVo.setSkuId(skuId);
            cartItemVo.setPrice(skuInfo.getPrice());
        }, threadPoolExecutor);
        //远程查询sku销售属性信息
        CompletableFuture<Void> skuSaleAttrFuture = CompletableFuture.runAsync(() -> {
            List<String> skuSaleAttrValue = productFeignService.getSkuSaleAttrValue(skuId);
            cartItemVo.setSkuAtr(skuSaleAttrValue);
        }, threadPoolExecutor);
        CompletableFuture.allOf(skuInfoFuture, skuSaleAttrFuture).get();
        redisUtil.hset(cartKey, skuId.toString(), cartItemVo);
        return cartItemVo;
    }

    /**
     * 购物车 获取购物项数据
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        return (CartItemVo) redisUtil.hget(getCartKey(), skuId.toString());
    }

    /**
     * 购物车 去购物车页面
     * 返回所有购物车数据
     */
    @Override
    public CartVo getCart() {
        String cartKey = getCartKey();
        CartVo cartVo = new CartVo();
        List<CartItemVo> collect = getCartItemVos(cartKey);
        if (CollectionUtil.isNotEmpty(collect)) {
            cartVo.setCartItemVos(collect);
            return cartVo;
        }
        return null;
    }

    public List<CartItemVo> getCartItemVos(String cartKey) {
        Collection<Object> values = redisUtil.hmget(cartKey).values();
        return values.stream().map(item -> (CartItemVo) item).collect(Collectors.toList());
    }

    /**
     * 登录时 合并购物车
     */
    @Override
    public void mergeCart(String userKey, Long id) {
        //游客购物车
        Map<Object, Object> hmget = redisUtil.hmget(CartConstant.CART_REDIS_PREFIX + userKey);
        hmget.forEach((k, v) -> {
            try {
                addCartItem(Long.parseLong((String) k), ((CartItemVo) v).getCount(), CartConstant.CART_REDIS_PREFIX + id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        redisUtil.del(CartConstant.CART_REDIS_PREFIX + userKey);
    }

    /**
     * 勾选购物项
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        redisUtil.hset(getCartKey(), skuId.toString(), cartItem);
    }

    /**
     *  购物车 修改数量 +1 -1
     */
    @Override
    public void countItem(Long skuId, Integer num) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        redisUtil.hset(getCartKey(), skuId.toString(), cartItem);
    }

    /**
     *  购物车 删除购物项
     */
    @Override
    public void deleteItem(Long skuId) {
        redisUtil.hdel(getCartKey(), skuId.toString());
    }

    /**
     * 订单确认页
     * 获取用户所有选中购物项
     */
    @Override
    public List<CartItemVo> getUserCartItem() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Long userId = userInfoTo.getUserId();
        if (userId != null) {
            String cartKey = CartConstant.CART_REDIS_PREFIX + userId;
            List<CartItemVo> cartItemVos = getCartItemVos(cartKey);
            return cartItemVos.stream()
                    .filter(CartItemVo::getCheck)
                    .map(item->{
                        //更新最新的价格,不能用缓存的价格
                        R price = productFeignService.getPrice(item.getSkuId());
                        String data = (String) price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    }).collect(Collectors.toList());
        } else {
            return null;
        }
    }

    /**
     * 根据登录状态   获取购物车的 key
     */
    private String getCartKey() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Long userId = userInfoTo.getUserId();
        String cartKey;
        if (userId != null) {
            cartKey = CartConstant.CART_REDIS_PREFIX + userId;
        } else {
            cartKey = CartConstant.CART_REDIS_PREFIX + userInfoTo.getUserKey();
        }
        return cartKey;
    }
}
